<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\console\service;

use app\common\library\helper;
use app\console\library\Tools;
use app\common\service\BaseService;
use app\console\model\User as UserModel;
use app\console\model\user\Grade as UserGradeModel;
use app\api\service\User as UserService;
use app\api\service\user\Grade as UserGradeService;
/**
 * 服务类：会员等级
 * Class UserGrade
 * @package app\console\service
 */
class UserGrade extends BaseService
{
    /**
     * 批量设置用户的会员等级
     * @param int $storeId
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setUserGrade(int $storeId)
    {
        // 获取所有会员等级
        $list = $this->getUsableList($storeId);
        // 遍历等级，根据升级条件 查询满足消费金额的用户列表，并且他的等级小于该等级
        $data = [];
        foreach ($list as $grade) {
            // 查询满足会员等级升级条件的用户列表
            $userList = UserModel::getUpgradeUserList($storeId, $grade, array_keys($data));
            // 遍历整理数据
            foreach ($userList as $user) {
                if (!isset($data[$user['user_id']])) {
                    $data[$user['user_id']] = [
                        'user_id' => $user['user_id'],
                        'old_grade_id' => $user['grade_id'],
                        'new_grade_id' => $grade['grade_id'],
                    ];
                }
            }
        }
        // 记录日志
        Tools::taskLogs('UserGrade', 'setUserGrade', [
            'storeId' => $storeId,
            'data' => $data
        ]);
        // 批量修改会员的等级
        return (new UserModel)->setBatchGrade($storeId, $data);
    }

     /**
     * 单独设置当前用户的会员等级
     * @param int $storeId
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setUserGradeNew(int $storeId, $userId = false)
    {
        if(!$userId){
            $userId = UserService::getCurrentLoginUserId();
        }
        // 获取所有会员等级
        $list = $this->getUsableList($storeId);
        // 遍历等级，根据升级条件 查询满足累计积分的用户列表，并且他的等级小于该等级
        $data = [];
        foreach ($list as $grade) {
            // 查询满足会员等级升级条件的用户列表
            $userList = UserModel::getUpgradeUserList($storeId, $grade, array_keys($data),$userId);
            // 遍历整理数据
            foreach ($userList as $user) {
                if (!isset($data[$user['user_id']])) {
                    $data[$user['user_id']] = [
                        'user_id' => $user['user_id'],
                        'old_grade_id' => $user['grade_id'],
                        'new_grade_id' => $grade['grade_id'],
                    ];
                }
            }
        }
        // 记录日志
        Tools::taskLogs('UserGrade', 'setUserGrade', [
            'storeId' => $storeId,
            'data' => $data
        ]);

        // 批量修改会员的等级
        return (new UserModel)->setBatchGrade($storeId, $data);
    }


    /**
     * 获取所有会员等级
     * @param int $storeId 商城ID
     * @return false|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function getUsableList(int $storeId)
    {
        return UserGradeModel::getUsableList($storeId);
    }

      /**
     * 获取最大的会员等级
     * @param int $storeId 商城ID
     * @return false|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function getMaxUsableList(int $storeId)
    {
        return UserGradeModel::getMaxUsableList($storeId);
    }

    

    /**
     * 获取大于当前会员等级权重的下一个等级
     * @param int $storeId 商城ID
     * @return false|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function getNextUsableList(int $storeId,int $weight)
    {
        return UserGradeModel::getNextUsableList($storeId,$weight);
    }


    //获取会员等级进度百分比
    public function getUserGradeDetail(int $storeId){
        $schedule = array();$userGradepoints=0;$percentage=0;
         // 当前用户信息
         $userInfo = UserService::getCurrentLoginUser(true);
         if($userInfo){
            $userInfo = $userInfo->toArray();
            $userGradepoints = $userInfo['expend_points'];//当前会员累计积分
             // 获取当前登录用户的会员等级信息
            $gradeInfo = UserGradeService::getCurrentGradeInfo();
            if($gradeInfo){
                $gradeInfo =$gradeInfo->toArray();
                $userGrade = $gradeInfo['grade_id'];//当前会员等级
                $userGradeweight = $gradeInfo['weight'];//当前会员等级权重
                //获取最大会员等级
                $maxGradelist = $this->getMaxUsableList($storeId)->toArray();
                if($userGrade ==  $maxGradelist['grade_id']){  //当前会员等级已经是最大的会员等级
                    $percentage = '100';
                }else{
                    // 获取下一会员等级
                    $nextlist = $this->getNextUsableList($storeId,$userGradeweight)->toArray();
                    $nextUpgrade = $nextlist['upgrade']['expend_points'];
                    $percentage = round($userGradepoints/$nextUpgrade,2)*100; //累计积分/下一等级的升级积分×100
                }
            }
         }
         
         $schedule = array('expend_points'=>$userGradepoints,'percentage'=>$percentage);

         return $schedule;

    }

}